package com.qfedu.spring.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @auther asus
 * @date 2022/4/26 16:35
 * 增强类，五种增强方法
 */
@Aspect
@Component
public class UserAdvice {
    @Pointcut("execution(* com.qfedu.spring.aop.service..*.*(..))")
    public void pointCut(){}

    //前置增强
//    前置增强 JoinPoint：连接点
    // TODO 讲解增强方法切入点参数
    @Before("pointCut()")
    public void before(JoinPoint joinPoint){

        System.out.println("前置增强执行了。。。。");
        Object target = joinPoint.getTarget();
        System.out.println("目标对象是："+target);
        System.out.println("方法名：" + joinPoint.getSignature().getName());
        System.out.println("参数是：" + Arrays.toString(joinPoint.getArgs()));
    }


    //后置增强
    @AfterReturning(value = "pointCut()",returning = "result")
    public Object  afterReturning(Object result){
        // result 目标方法的返回值
        System.out.println("后置增强执行了。。。。");

        return result;
    }


    //最终增强
    @After("pointCut()")
    public void after(){
        System.out.println("最终增强执行了。。。。");
    }


    //环绕增强  ProceedingJoinPoint是JoinPoint的子接口
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint jp){
        Object result= null;
        try {
            System.out.println("环绕增强执行了。。前。。");
            // 决定目标方法是否继续执行 result:目标方法的返回值
            result = jp.proceed();
            System.out.println("环绕增强执行了。。后。。");
        }catch (Throwable e){
            e.printStackTrace();
        }
        return result;
    }


    //异常抛出增强
    @AfterThrowing(value = "pointCut()",throwing = "e")
    public void throwing(Exception e){

        System.out.println("异常抛出增强执行了。。。。");
        System.out.println("抛出的异常是：" + e.getMessage());

    }

}
